package org.smile.auth;

import org.smile.auth.request.Request;
import org.smile.auth.session.Manager;
import org.smile.auth.session.Session;
import org.smile.util.StringUtils;
import org.smile.util.UUIDGenerator;

public class AuthUtils {
    private static Manager manager;

    private static AuthConfigInit configInit;

    public static void init(AuthConfigInit init){
        configInit=init;
        manager=init.initManager();
    }
    public static Session getSession(String sessionId){
        return manager.findSession(sessionId);
    }

    public static Request getRequest(){
        return configInit.getRequest();
    }

    public static Session findSession(){
        Session session=null;
        Request request= configInit.getRequest();
        String token=request.getToken();
        if(StringUtils.notBlank(token)){
            session= manager.findSessionByToken(token);
            if(session!=null){
                return session;
            }
        }
        String sessionId= request.getSessionId();;
        if(StringUtils.notBlank(sessionId)){
            session= manager.findSession(token);
            if(session!=null){
                return session;
            }
        }
        return null;
    }

    public static Session getSession(){
        Session session= findSession();
        if(session==null){
            session= manager.createSession();
            session.initToken(UUIDGenerator.uuid32());
            return session;
        }
        return session;
    }

}
